import React, { useEffect, useState, useRef } from 'react';
import { connect, history } from 'umi';
import { Form, Button, Col, Row, Space, Card, notification } from 'antd';
import FormCondition from '@/components/FormCondition';
import uploadOss from '@/utils/aliOssUpload';
import { goodsType_status } from '@/common/contact';
import moment from 'moment';
import PackagingModel from '@/components/PackagingRadioModel';
import SeckilSetting from './components/SeckilSetting';
import { dateDisabled } from '@/common/regular';
import './index.less';

const CreateOnDemand = (props) => {
  const { history, loading, dispatch } = props;
  const { location } = history;
  const { query } = location;
  const { id } = query;
  const [data, setData] = useState({});
  const [seckilList, setSeckilList] = useState([]);
  const seckilRef = useState(null);
  const { defaultList = [] } = data;
  const [form] = Form.useForm();
  const [defaultSetting, setDefaultSetting] = useState({});
  const { preheatFlag = '' } = defaultSetting;
  useEffect(() => {
    if (id) {
      dispatch({
        type: 'liveStreaming/fetchGoodsSecKillDetail',
        payload: { secKillId: id },
        callback: (e) => {
          const { secKillSkuList = [], secKill = {}, secKillGoodsInfo = {} } = e;
          const {
            goodsId,
            secKillStartTime,
            secKillEndTime,
            reserveFlag = '',
            preheatFlag = '',
          } = secKill;
          setSeckilList([
            {
              id: goodsId,
              ...secKillGoodsInfo,
              goodsSkuList: secKillSkuList,
              ...secKill,
            },
          ]);
          setData({
            ...secKill,
            reserveFlag: reserveFlag.split(','),
            preheatFlag: preheatFlag.split(','),
            secKillStartTime: [moment(secKillStartTime), moment(secKillEndTime)],
            defaultList: [
              {
                id: goodsId,
                ...secKillGoodsInfo,
                goodsSkuList: secKillSkuList,
              },
            ],
          });
        },
      });
    }
  }, []);
  useEffect(() => {
    if (id && data.id) {
      form.setFieldsValue({
        preheatFlag: data.preheatFlag,
      });
      setDefaultSetting({
        preheatFlag: data.preheatFlag,
      });
    }
  }, [data]);
  const fetchRoleEdit = () => {
    let SecKillData = seckilRef.current.getSecKillData();
    const { hasSku, renderList } = SecKillData;
    console.log(renderList);
    let flag = renderList.reduce((item, val) => {
      if (!item) {
        return item;
      } else {
        if (
          (!val.secKillPrice && val.secKillPrice !== 0) ||
          (!val.secKillStock && val.secKillStock !== 0)
        ) {
          return false;
        } else {
          return item;
        }
      }
    }, true);
    if (renderList.length === 0) {
      return notification.warning({
        message: '温馨提示',
        description: `请选择或填写秒杀商品`,
      });
    } else if (!flag) {
      return notification.warning({
        message: '温馨提示',
        description: `请将秒杀商品库存和数量填写完整 `,
      });
    } else {
      let data = {};
      data.secKillPrice = renderList.reduce((item, val) => {
        console.log(val, val.secKillPrice);
        if (item <= val.secKillPrice && item !== 0) {
          return item;
        } else {
          return val.secKillPrice;
        }
      }, 0);
      data.secKillStock = renderList.reduce((item, val) => {
        return item + val.secKillStock;
      }, 0);
      data.goodsId = renderList[0].id;
      if (hasSku) {
        data.secKillSkuList = renderList.map((item) => {
          return {
            secKillPrice: item.secKillPrice,
            secKillStock: item.secKillStock,
            skuId: item.skuId,
          };
        }, []);
      }
      form.validateFields().then(async (values) => {
        console.log(values);
        const { secKillStartTime, reserveFlag = [], preheatFlag = [] } = values;
        dispatch({
          type: 'liveStreaming/fakeGoodsSecKill',
          payload: {
            ...values,
            ...data,
            reserveFlag: reserveFlag.toString(),
            preheatFlag: preheatFlag.toString(),
            secKillStartTime: moment(secKillStartTime[0]).format('YYYY-MM-DD HH:mm'),
            secKillEndTime: moment(secKillStartTime[1]).format('YYYY-MM-DD HH:mm'),
          },
          callback: (e) => {
            history.goBack();
          },
        });
      });
    }
  };
  function disabledDateTime(current) {
    console.log(current, 1231233123);
    // 获取当前时间
    const currentDate = new Date();
    const currentHour = currentDate.getHours();
    const currentMinute = currentDate.getMinutes();
    if (moment(current).isAfter(currentDate, 'day')) {
      return null;
    } else if (moment(current).isBefore(currentDate, 'day')) {
      return {
        disabledHours: () => Array.from({ length: 24 }, (_, i) => i),
        disabledMinutes: () => Array.from({ length: 60 }, (_, i) => i),
      };
    } else if (moment(current).hour() > moment(currentDate).hour()) {
      return {
        disabledHours: () => Array.from({ length: currentHour }, (_, i) => i),
      };
    } else {
      return {
        disabledHours: () => Array.from({ length: currentHour }, (_, i) => i),
        disabledMinutes: () => Array.from({ length: currentMinute }, (_, i) => i),
      };
    }
  }

  const formItemsGroup3 = [
    {
      type: 'noForm',
      formItem: (
        <PackagingModel
          disabled={id}
          list={defaultList}
          onChange={setSeckilList}
          detail={data}
        ></PackagingModel>
      ),
    },

    {
      type: 'noForm',
      formItem: (
        <SeckilSetting
          disabled={id}
          list={seckilList}
          ref={seckilRef}
          detail={data}
        ></SeckilSetting>
      ),
    },
  ];
  const formItems = [
    {
      label: '活动名称',
      name: 'secKillName',
      disabled: id,
      maxLength: 10,
    },
    {
      label: '活动时间',
      name: 'secKillStartTime',
      type: 'rangePicker',
      disabled: id,
      showTime: 'HH:mm',
      format: 'YYYY-MM-DD HH:mm',
      end: 'secKillEndTime',
      disabledDate: dateDisabled,
      disabledTime: disabledDateTime,
    },
    {
      label: '活动预热',
      name: 'preheatFlag',
      rules: [{ required: false }],
      disabled: id,
      type: 'checkbox',
      onChange: (e) => {
        console.log(e);
        setDefaultSetting({
          ...defaultSetting,
          preheatFlag: e,
        });
      },
      select: {
        1: (
          <div>
            开启活动预热
            <span style={{ color: '#999999' }}>(开启预热后，活动信息会展示在商品详情页)</span>
          </div>
        ),
      },
    },
    {
      label: '预热时间',
      name: 'preheatHour',
      disabled: id,
      visible: preheatFlag.toString() === '1',
      type: 'number',
      max: 240,
      min: 0,
      placeholder: '最多240小时，填0代表立即开始预热',
    },
    {
      label: '活动标签',
      name: 'secKillTag',
      disabled: id,
      maxLength: 5,
      rules: [{ required: false }],
    },
  ];
  const formItemsGroup4 = [
    {
      label: '活动预热',
      name: 'reserveFlag',
      rules: [{ required: false }],
      type: 'checkbox',
      select: {
        1: (
          <div>
            开启秒杀预约
            <span style={{ color: '#999999' }}>
              (开启预约后，只有成功预约的用户才能参与秒杀活动)
            </span>
          </div>
        ),
      },
    },
  ];
  return (
    <Card title={id ? '编辑秒杀' : '新建秒杀 '} style={{ position: 'relative' }}>
      <Row>
        <Col span={18}>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">商品信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup3}
            initialValues={{ ...data }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">活动信息</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItems}
            initialValues={{
              ...data,
            }}
          ></FormCondition>
          <div className="createLive-manage-part">
            <div className="createLive-part-title">
              <div className="createLive-title-line"></div>
              <div className="createLive-part-title-word">预约设置</div>
            </div>
          </div>
          <FormCondition
            form={form}
            formItems={formItemsGroup4}
            initialValues={data}
          ></FormCondition>
        </Col>
        <div className="create_upload_btn">
          {id ? (
            <Button
              onClick={() =>
                dispatch({
                  type: 'login/findAccessId',
                  payload: {
                    pathname: '/marketingModule/seckillList',
                  },
                })
              }
            >
              返回
            </Button>
          ) : (
            <Button onClick={() => fetchRoleEdit()} type="primary">
              保存商品
            </Button>
          )}
        </div>
      </Row>
    </Card>
  );
};
export default connect(({ loading }) => ({
  loading: loading.effects['liveStreaming/fetchVideoCourseDetail'],
}))(CreateOnDemand);
